const { Router } = require('express');
const logger = require('../utils/logger');
const Resp = require('../model/resp');
const Staritem = require('../model/staritem');
const starMapper = require('../mapper/starMapper');
const GoodApi = require('../api/goodApi');

const router = Router();

router.all('/', function (req, res, next) {
  res.json(Resp.ok("这里是收藏夹服务", 1));
});

/**
 * 分页查询收藏夹
 */
router.get('/user/:uid/starpage', async function (req, res, next) {
  let params = req.query; //pageNum, pageSize, keyword
  if(params.pageNum<1 || params.pageSize<0){
      return res.json(Resp.fail("请给定正确的页号和条数", -1, params));
  }
  const uid = req.params.uid;
  logger.debug(`uid: ${uid}`);
  let count_all = await starMapper.count_all_by_uid(uid);
  if (count_all == 0) {
      res.json(Resp.ok("查询成功，收藏夹空空如也", 2, { glist: [], gtotal: count_all }));
      return;
  }
  //去本地数据库查出符合条件的商品
  params.uid = uid;
  logger.debug(params);
  params.keyword = params.keyword??'';
  let { count, rows } = await starMapper.sel_page_options(params);
  if (rows.length == 0) {
      res.json(Resp.ok("查询成功，没有相关的商品", 3, { glist: [], gtotal: count }));
  } else {
    logger.debug(rows);
    res.json(Resp.ok("查询收藏夹成功", 1, { glist: rows, gtotal: count }));
  }    
});

/**
 * 添加收藏
 */
router.post('/user/:uid/star', async(req, res, next) => {
  let uid = req.params.uid;
  let gid = req.query.gid;
  const count = await Staritem.count({where:{uid,gid}});
  if ( count == 1 ) {
    return res.json(Resp.fail("该商品已经添加到收藏夹中", -1, {uid,gid}));
  }
  const simpleGoodVos = await GoodApi.query_simple_goodvo_by_gids({gids: [gid]});
  logger.debug(simpleGoodVos);
  if(simpleGoodVos.length == 0) {
    return res.json(Resp.fail("该商品不存在", -2, {gid}));
  }
  const {gname,gprice,gstate,img} = simpleGoodVos[0];
  await Staritem.create({uid,gid,gname,gprice,gstate,img});
  res.json(Resp.ok("收藏成功", 1));
})


/**
 * 取消收藏
 */
router.delete('/user/:uid/star', async (req, res, next) => {
  let uid = req.params.uid;
  let gid = req.query.gid;
  let rst = await Staritem.destroy({where: {uid, gid}});
  if(rst == 0) {
    return res.json(Resp.fail("收藏夹中没有这件商品", -1, { uid, gid }));
  }
  res.json(Resp.ok("成功取消收藏", 1));
})

module.exports = router;
